//
//  SendTextViewController.m
//  XiangMuB
//
//  Created by lanou3g on 16/8/12.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "SendTextViewController.h"

#import "SendTextView.h"
#import "ToolBarView.h"
#import "PersonMessageTableViewController.h"
#import "ContentModel.h"
#import "ObjectIdArrayModel.h"
#import "PhotoView.h"
#import "PhotoModel.h"
#import "PhotoCollectionViewCell.h"
#import "ShowBigImage.h"
#import "CellContentModel.h"
#import "LocalDataHandle.h"



@interface SendTextViewController ()<UITextViewDelegate,ToolBarViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (strong, nonatomic) SendTextView *sendTextView;
@property (strong, nonatomic) ToolBarView *toolBarView;

@property (strong, nonatomic) NSMutableArray *getObjectIdArray;
@property (strong, nonatomic) NSMutableArray *previouArray;

@property (strong, nonatomic) NSString *objectIdString;


@property (strong, nonatomic) NSArray<PhotoModel *> *lastSelectModels;
@property (strong, nonatomic) NSArray *dataSource;


//UICollectionView
@property (strong, nonatomic) UICollectionView *topCollectionView;

@end

@implementation SendTextViewController

- (NSMutableArray *)tagArray{
    
    if (_tagArray == nil) {
        _tagArray = [NSMutableArray array];
    }
    
    return _tagArray;
    
}

- (UICollectionView *)topCollectionView{
    
    if (_topCollectionView == nil) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width - 9)/4, ([UIScreen mainScreen].bounds.size.width - 9)/4);

        layout.minimumInteritemSpacing = 3;
        layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
        layout.itemSize = CGSizeMake(100, 100);
        
        _topCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 300) collectionViewLayout:layout];
        
        [_topCollectionView registerClass:[PhotoCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        _topCollectionView.backgroundColor = [UIColor yellowColor];
        
        _topCollectionView.delegate = self
        ;
        _topCollectionView.dataSource = self;
        
        
    }
    
    return _topCollectionView;
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    self.view.backgroundColor = [UIColor brownColor];
    self.navigationItem.title = @"发表文字";
    
    self.objectIdString = [[NSUserDefaults standardUserDefaults] objectForKey:@"objectId"];
//    NSLog(@"=666666===%@",self.objectIdString);
//    
//    NSLog(@"=========tag %ld",(long)self.buttonTag);
    
    
    [self setupSubviews];
    
    [self setupTextView];
 
    
   
    
}


- (void)setupSubviews{

    if (self.buttonTag == 0) {
        
        [self showPhotos];
        
        
  
        [self.view addSubview:self.topCollectionView];
        
    } else if (self.buttonTag == 1) {
        
        [self setupToolBarView];
       
    }
    

}



- (void)setupTextView{
    
    self.sendTextView = [[SendTextView alloc] init];
    //    self.sendTextView.frame = self.view.bounds;
    
    self.sendTextView.frame = CGRectMake(0, 64, self.view.frame.size.width, 50);
    self.sendTextView.placeholder = @"在此输入23435465756867879";
    self.sendTextView.backgroundColor = [UIColor clearColor];
    self.sendTextView.placeholderColor = [UIColor redColor];
    
    self.sendTextView.delegate = self;
    [self.view addSubview:self.sendTextView];
}

- (void)setupToolBarView{
    
    self.toolBarView = [[ToolBarView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 90, self.view.frame.size.width, 90)];
    self.toolBarView.backgroundColor = [UIColor brownColor];
    self.toolBarView.deleate = self;
    
    [self.view addSubview:self.toolBarView];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    
    
}


#pragma mark getter method

- (NSMutableArray *)getObjectIdArray{
    
    if (_getObjectIdArray == nil) {
        _getObjectIdArray = [NSMutableArray array];
    }
    
    return _getObjectIdArray;
}

- (NSMutableArray *)previouArray{
    
    if (_previouArray == nil) {
        _previouArray = [NSMutableArray array];
    }
    
    return _previouArray;
}



#pragma mark UITextViewDelegate method

- (void)textViewDidChange:(UITextView *)textView{
    
    self.toolBarView.sendButton.userInteractionEnabled = YES;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self.view endEditing:YES];
}

#pragma mark notification method

- (void)keyboardWillChangeFrame:(NSNotification *)notification{
    
    CGRect endFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
        
        self.toolBarView.transform = CGAffineTransformMakeTranslation(0, endFrame.origin.y - [UIScreen mainScreen].bounds.size.height);
        
    }];
    
    
}

#pragma mark toolbarViewdelegate method

- (void)getTagArray:(NSArray *)tags{
    
    [self.tagArray addObjectsFromArray:tags];
    
    NSLog(@"tagarray = %@",self.tagArray);
}

- (void)dismissViewController{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)sendMessage{
    
    
    PersonMessageTableViewController *person = [[PersonMessageTableViewController alloc] init];
    
    [self saveDataInCloud:person];
    
    
    
    [self.navigationController pushViewController:person animated:YES];
    NSLog(@"发表消息");
}

- (void)saveDataInCloud:(PersonMessageTableViewController *)person{
    
    ContentModel *model = [[ContentModel alloc] init];
    
    CellContentModel *cellModel = [[CellContentModel alloc] init];
    cellModel.textViewString = self.sendTextView.text;
    [cellModel.imageArray addObjectsFromArray:self.dataSource];
    [cellModel.tagArrays addObjectsFromArray:self.tagArray];
    
    [[LocalDataHandle shareDataHandle] saveDataWithCellContentModleToLocal:cellModel];
    NSLog(@"%@",NSHomeDirectory());
    
    
//    model.file = [AVFile fileWithName:@"CellContentModel" data:data];
//    [model.file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//        if (error == 0) {
//            NSLog(@"图片保存成功");
//        }
//        
//    }];
    
    model.contentString = self.sendTextView.text;
    
//    ObjectIdArrayModel *arrayModel = [[ObjectIdArrayModel alloc] init];
    
    
    [model saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        if (!error) {
            
            [self.getObjectIdArray removeAllObjects];
            [self.getObjectIdArray addObject:model.objectId];
            NSLog(@"保存数据成功:%@====%@",model.contentString,model.objectId);
            //            [ObjectIdArrayModel shareObject];
            
            
            
            NSLog(@"---------%@",self.objectIdString);
            ObjectIdArrayModel *arrayModel = [ObjectIdArrayModel objectWithObjectId:self.objectIdString];
            //            arrayModel.array = [NSMutableArray array];
            
            
            [arrayModel fetchInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                
                [self.previouArray removeAllObjects];
                [self.previouArray addObjectsFromArray:object[@"array"]];
                
                NSLog(@"self.previouarray = %@",self.previouArray);
                
                
                
                
                NSMutableArray *arra = [NSMutableArray array];
                
                
                [arra addObjectsFromArray:self.getObjectIdArray];
                
                NSLog(@"getarray = %@",self.getObjectIdArray);
                
                
                
                [arrayModel addObjectsFromArray:arra forKey:@"array"];
                [arrayModel saveInBackground];
                
                
            }];
            
            
            
            
            
            
            
        } else {
            
            NSLog(@"保存数据失败");
        }
        
    }];
    
    
    
    
    
    //    ObjectIdArrayModel *arrayId = [[ObjectIdArrayModel alloc] init];
    //    arrayId.array = [NSMutableArray array];
    
    
    
}








- (void)showPhotos{
    
    PhotoView *photoView = [[PhotoView alloc] init];
    
    photoView.maxSelectCount = 5;
    photoView.maxPreviewCount = 20;
    
    __weak typeof(self) weakself = self;
    [photoView showWithSender:self animate:YES lastSelectPhotoModels:self.lastSelectModels completion:^(NSArray<UIImage *> *selectPhotos, NSArray<PhotoModel *> *photoModels) {
        
        weakself.dataSource = selectPhotos;
        weakself.lastSelectModels = photoModels;
        
        [weakself.topCollectionView reloadData];
        [self setupToolBarView];
        [self.sendTextView becomeFirstResponder];
    }];
    
    
}



#pragma mark UICollectionViewDelegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifierCell = @"cell";
    
    PhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifierCell forIndexPath:indexPath];
    
    cell.selectButton.hidden = YES;
    cell.imagesVie.image = self.dataSource[indexPath.row];
    cell.imagesVie.contentMode = UIViewContentModeScaleAspectFill;
    cell.imagesVie.clipsToBounds = YES;
    
    
    return cell;
}

#pragma mark UICollectionViewDatasource

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    PhotoCollectionViewCell *cell = (PhotoCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    [self.sendTextView resignFirstResponder];
    
    [ShowBigImage showBigImage:cell.imagesVie];
    
}



- (void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];

    if (self.buttonTag == 1) {
        [self.sendTextView becomeFirstResponder];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
